// 通过外部js注入的形式绕过scp
const script = document.createElement('script');
script.src = chrome.runtime.getURL('src/injected.js');
script.defer = true;
(document.head || document.documentElement).appendChild(script);

// 脚本注入完成后，再增加操作逻辑
script.onload = () => {
  const shadowTag = document.querySelector('mahd-web-extension');
  const shadowRoot = shadowTag.shadowRoot;
  const imgIcon = shadowRoot.querySelector('#imgIcon');
  const imgExplain = shadowRoot.querySelector('#imgExplain');

  imgIcon.src = chrome.runtime.getURL('src/assets/icon-float.png');
  imgExplain.src = chrome.runtime.getURL('src/assets/icon-float.png');

  let explainValue = "";

  // ----------------- 拖动功能 start-----------------  
  let startX = 0;
  let startY = 0;

  const handleMouseMove = (event, diffX, diffY) => {
    let moveX = event.clientX - diffX;
    let moveY = event.clientY - diffY;

    moveX = Math.max(0, Math.min(moveX, window.innerWidth - imgIcon.offsetWidth));
    moveY = Math.max(0, Math.min(moveY, window.innerHeight - imgIcon.offsetHeight));

    imgIcon.style.left = `${moveX}px`;
    imgIcon.style.top = `${moveY}px`;
    imgIcon.style.width = '60px';
    imgIcon.style.height = '60px';
  };

  const handleMouseUp = (event) => {
    imgIcon.style.width = '50px';
    imgIcon.style.height = '50px';
    document.onmousemove = null;
    document.onmouseup = null;

    const distanceX = Math.abs(event.clientX - startX);
    const distanceY = Math.abs(event.clientY - startY);

    if (distanceX === 0 && distanceY === 0) {
      // 如果没有移动，说明是点击，打开边侧栏
      chrome.runtime.sendMessage({ action: "getBrowserVersion" }, (response) => {
        if (response && response.version) {
          const browserVersion = response.version;
          // 判断浏览器版本是否低于 114
          if (browserVersion < 114) {
            alert(`您的浏览器版本过低（${browserVersion}），请升级到 114 或更高版本。`);
          }
          chrome.runtime.sendMessage({ action: 'openSidebar' }, response => {
          });
        } else {
          console.error("无法获取浏览器版本");
        }
      });
    }
  };
  imgIcon.onmousedown = (event) => {
    startX = event.clientX;
    startY = event.clientY;
    const diffX = event.clientX - imgIcon.offsetLeft;
    const diffY = event.clientY - imgIcon.offsetTop;

    document.onmousemove = (event) => handleMouseMove(event, diffX, diffY);
    document.onmouseup = (event) => handleMouseUp(event);
  };

  const targetDiv = shadowRoot.querySelector('#mahd-extension__area');

  const observer = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const { width, height } = entry.contentRect;
      // console.log('content.js targetDiv', width, height);

      imgIcon.style.top = (height - 60) + 'px';
      imgIcon.style.left = (width - 60) + 'px';
    }
  });
  // 开始观察目标元素
  observer.observe(targetDiv);

  // ----------------- 拖动功能 end-----------------

  // ----------------- 解释功能 start---------------
  const handleTextSelection = () => {
    setTimeout(() => {
      const selected = window.getSelection().toString().trim();
      if (selected.length > 0) {
        const range = window.getSelection().getRangeAt(0);
        const rect = range.getBoundingClientRect();

        imgExplain.style.left = `${rect.right + window.scrollX + 8}px`;
        imgExplain.style.top = `${rect.top + window.scrollY - 24}px`;

        imgExplain.classList.add('visible');
        explainValue = selected;
      } else {
        imgExplain.classList.remove('visible');
      }
    }, 20);
  };

  const handleExplainClick = () => {
    imgExplain.classList.remove('visible');
    window.getSelection().removeAllRanges();
    chrome.runtime.sendMessage({ action: "getBrowserVersion" }, (response) => {
      if (response && response.version) {
        const browserVersion = response.version;
        console.log(browserVersion)
        // 判断浏览器版本是否低于 114
        if (browserVersion < 114) {
          alert(`您的浏览器版本过低（${browserVersion}），请升级到 114 或更高版本。`);
        }
        chrome.runtime.sendMessage({ action: 'openSidebar' }, () => {
          setTimeout(() => {
            chrome.runtime.sendMessage({
              action: 'explain',
              text: explainValue,
            });
          }, 500);
        });
      } else {
        console.error("无法获取浏览器版本");
      }
    });
  };

  document.addEventListener('mouseup', handleTextSelection);
  imgExplain.addEventListener('click', handleExplainClick);

  document.addEventListener('mousedown', (event) => {
    if (!imgExplain.contains(event.target)) {
      imgExplain.classList.remove('visible');
    }
  });
  // ----------------- 解释功能 end---------------

  // 初始化图标是否显示
  const initializeIcons = () => {
    chrome.storage.sync.get(['xuanfu_switch', 'xuanqu_switch'], (result) => {
      imgIcon.style.display = result.xuanfu_switch ? 'block' : 'none';
      imgExplain.style.display = result.xuanqu_switch ? 'block' : 'none';
    });
  };

  initializeIcons();

  // 监听消息来自popup.js -> serivce-worker.js，图标是否显示
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.xuanfu_switch_content !== undefined) {
      imgIcon.style.display = request.xuanfu_switch_content ? 'block' : 'none';
      return true;
    }
    if (request.xuanqu_switch_content !== undefined) {
      imgExplain.style.display = request.xuanqu_switch_content ? 'block' : 'none';
      return true;
    }
  });
};

function getDOMData() {
  const protocol = window.location.protocol;

  // 对特定协议的页面返回错误信息
  if (['edge:', 'chrome:', 'opera:', 'safari:'].includes(protocol)) {
    return { dom: 'error page', success: false };
  }

  // 返回页面 DOM 信息和成功标志
  return {
    dom: document.documentElement.outerHTML,
    success: true,
  };
}

/**
 * 监听消息，抓取 DOM 信息
 */
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // console.log('content.js receive message', request);

  // 只处理获取 DOM 的请求
  if (request.action === 'getDOM') {
    const response = getDOMData();
    sendResponse(response);

    // 表示异步 sendResponse 调用
    return true;
  }
});